package cn.com.taiji.oospub.wechat.controller.card;


import cn.com.taiji.model.finals.SessionNames;
import cn.com.taiji.oospub.wechat.common.MySessionNames;
import cn.com.taiji.oospub.wechat.common.ObjectToXML;
import cn.com.taiji.oospub.wechat.common.OrderSend;
import cn.com.taiji.oospub.wechat.common.tool.NetTools;
import cn.com.taiji.oospub.wechat.common.tool.TimeTools;
import cn.com.taiji.oospub.wechat.common.util.HttpUtil;
import cn.com.taiji.oospub.wechat.common.wxpay.common.RandomStringGenerator;
import cn.com.taiji.oospub.wechat.common.wxpay.common.XMLParser;
import cn.com.taiji.oospub.wechat.common.wxpay.pay.*;
import cn.com.taiji.oospub.wechat.controller.BaseLogController;
import cn.com.taiji.oospub.wechat.entity.*;
import cn.com.taiji.oospub.wechat.model.CardStoredModel;
import cn.com.taiji.oospub.wechat.model.MemberBaseInfoModel;
import cn.com.taiji.oospub.wechat.service.*;
import cn.com.taiji.pub.StringTools;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.dreamyoung.mprelation.AutoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Controller
@RequestMapping("wx/mealCard")
public class MealCardController extends BaseLogController {

    @Value("${kongxc_pos_http_server_url}")
    private String kongxc_pos_http_server_url;
    @Value("${PROPASS}")
    public String PROPASS;
    @Value("${QR_PASSWORD}")
    public String QR_PASSWORD;
    @Value("${CUS_NAME}")
    public String CUS_NAME;
    @Value("${PROJECT_CODE}")
    public String PROJECT_CODE;
    @Value("${appID}")
    public String appID;
    @Value("${chuzhika_num}")
    private String chuzhika_num;
    @Value("${chuzhika_faFang}")
    private String chuzhika_faFang;
    @Value("${POS_URL}")
    private String POS_URL;
    @Autowired
    private OrderSend orderSend;
    private static Map<String, CoursesOrders> userMap = new HashMap<>();

    @Autowired
    private ICustomerMinMumService customerMinMumService;
    @Autowired
    private IMemberBaseInfoService memberBaseInfoService;
    @Autowired
    private IDiancanSchoolurlService diancanSchoolurlService;
    @Autowired
    public UnifiedorderService unifiedorderService;
    @Autowired
    public IOrderCodeService orderCodeService;
    @Autowired
    public IMemberStoreOrderService memberStoreOrderService;
    @Autowired
    public ICoursesService coursesService;
    @Autowired
    public ICoursesOrdersService coursesOrdersManager;
    @Autowired
    public IMealTimeService mealTimeService;
    @Autowired
    public IAccesstokensaveService accesstokensaveService;
    @Autowired
    public Signature signature;
    @Autowired
    public AutoMapper autoMapper;


    /**
     * 查找所有餐卡
     *
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/GetAllMealCard", method = RequestMethod.POST)
    @ResponseBody
    public String GetAllMealCard(Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        String idNumber = member.getIdNumber();
        if (StringUtils.hasText(idNumber)) {
            HttpUtil send = new HttpUtil(kongxc_pos_http_server_url);
            ObjectToXML toXml = new ObjectToXML();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String accountXml = toXml.requestAccountAllXMLKongxc(PROPASS, CUS_NAME, member.getSchool().getCode(), member.getIdNumber(), member.getZfPasswd(), uuid);
            String responseAccountXml = null;
            boolean isFail = false;
            try {
                responseAccountXml = send.sendToBoss(accountXml);
            } catch (Exception e) {
                e.printStackTrace();
                logger.debug(e.getMessage());
                isFail = true;
            }
            if (!isFail && !"null".equals(responseAccountXml)) {
                String responseAccount = toXml.resolveReponseAccountXml(responseAccountXml, request);
                Double realAccount = 0.0;
                if ("0000".equals(responseAccount)) {
                    List<MemberBaseInfoModel> accountList = toXml.resolveReponseAccountXml(responseAccountXml);
                    ArrayList<MemberBaseInfoModel> czAccountlist = new ArrayList<>();
                    ArrayList<MemberBaseInfoModel> bzAccountlist = new ArrayList<>();
                    if (accountList.size() > 0) {
                        for (MemberBaseInfoModel memberAccount : accountList) {
                            realAccount += (memberAccount.getAmount() == null ? 0.00d : memberAccount.getAmount());
                            if (chuzhika_num.equals(memberAccount.getAccountType())) {
                                czAccountlist.add(memberAccount);

                            } else if (chuzhika_faFang.equals(memberAccount.getAccountType())) {
                                bzAccountlist.add(memberAccount);

                            }
                        }
                        model.addAttribute("result", "success");
                        model.addAttribute("realAccount", realAccount);
                        model.addAttribute("czAccountlist", czAccountlist);
                        model.addAttribute("bzAccountlist", bzAccountlist);
                    } else {
                        model.addAttribute("result", false);
                        model.addAttribute("message", "用户未开通账户或账户已过期");
                    }
                } else {
                    model.addAttribute("result", false);
                    model.addAttribute("message", "未查询到餐卡信息");
                }
            }
        } else {
            model.addAttribute("result", false);
            model.addAttribute("message", "未查询到餐卡信息");
        }
        System.out.println(JSONObject.toJSONString(model));
        return JSONObject.toJSONString(model);
    }


    /**
     * 查找储值餐卡
     *
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/GetMealCard", method = RequestMethod.POST)
    @ResponseBody
    public String GetMealCard(Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        String idNumber = member.getIdNumber();
        if (StringUtils.hasText(idNumber)) {
            HttpUtil send = new HttpUtil(kongxc_pos_http_server_url);
            ObjectToXML toXml = new ObjectToXML();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            String accountXml = toXml.requestAccountXML(PROPASS, CUS_NAME, member.getSchool().getCode(), member.getIdNumber(), member.getZfPasswd(), uuid);
            String responseAccountXml = null;
            boolean isFail = false;
            try {
                responseAccountXml = send.sendToBoss(accountXml);
            } catch (Exception e) {
                e.printStackTrace();
                logger.debug(e.getMessage());
                isFail = true;
            }
            if (!isFail) {
                String responseAccount = toXml.resolveReponseAccountXml(responseAccountXml, request);
                Double realAccount = 0.0;
                if ("0000".equals(responseAccount)) {
                    List<MemberBaseInfoModel> accountList = toXml.resolveReponseAccountXml(responseAccountXml);
                    if (accountList.size() > 0) {
                        for (MemberBaseInfoModel memberAccount : accountList) {
                            realAccount += (memberAccount.getAmount() == null ? 0.00d : memberAccount.getAmount());
                        }
                        model.addAttribute("accountList", accountList);
                        model.addAttribute("result", "success");
                        model.addAttribute("money", realAccount);
                    } else {
                        model.addAttribute("result", false);
                        model.addAttribute("message", "用户未开通账户或账户已过期");
                    }
                } else {
                    model.addAttribute("result", false);
                    model.addAttribute("message", "未查询到餐卡信息");
                }
            }
        } else {
            model.addAttribute("result", false);
            model.addAttribute("message", "未查询到餐卡信息");
        }
        model.addAttribute("openId", member.getOpenid());
        return JSONObject.toJSONString(model);
    }


    /**
     * 餐卡储值(获取js校验码)
     *
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/GetMealCardStore", method = RequestMethod.POST)
    @ResponseBody
    public String GetMealCardStore(Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        assert member != null;
        String amount = request.getParameter("amount");
        String accountId = request.getParameter("accountId");
        String beforeAmount = request.getParameter("balance");
        String afterAmount = Double.valueOf(beforeAmount) + Double.valueOf(amount) + "";
        String orderCode = PROJECT_CODE + TimeTools.calendar2String(Calendar.getInstance(), "yyyyMMdd-HHmmss-SSS") + UUID.randomUUID().toString().substring(0, 4);
        MemberStoreOrder order = new MemberStoreOrder();
        order.setFlowNo(orderCode);
        order.setIsPay("0");
        order.setActualAmount(Double.valueOf(amount));
        order.setCreateTime(LocalDateTime.now());
        order.setCustomerId(member.getId());
        order.setAccountId(accountId);
        order.setBeforeAmount(Double.valueOf(beforeAmount));
        order.setAfterAmount(Double.valueOf(afterAmount));
        order.setUpdateOut("0");
        //获取access_token开始----------
        String accessToken = accesstokensaveService.query().one().getAccessToken();
        //-----获取access_token结束----------
        WxPaySendData data = new WxPaySendData();
        data.setAttach("zfcs");
        data.setBody(orderCode);
        String url = diancanSchoolurlService.findByProperty("school_code", member.getSchool().getCode()).getSchoolUrl();
        url += "/weixin/notityStore";
        data.setNotifyUrl(url);
        data.setNonceStr(RandomStringGenerator.getRandomStringByLength(32));
        data.setOpenid(member.getOpenid());
        data.setOutTradeNo(orderCode);

        int payMoney = (int) (Double.valueOf(amount) * 100);
        data.setTotalFee(payMoney);
        String returnXml = unifiedorderService.postReturnXml(data, request);
        try {
            Map<String, Object> mapReturn = XMLParser.getMapFromXML(returnXml);
            String return_code = (String) mapReturn.get("return_code");
            String return_msg = (String) mapReturn.get("return_msg");
            if ("SUCCESS".equalsIgnoreCase(return_code)) {
                Map<String, Object> mapToJsp = new HashMap<String, Object>();
                String prepay_id = (String) mapReturn.get("prepay_id");
                mapToJsp.put("appId", appID);
                mapToJsp.put("timeStamp", Calendar.getInstance().getTimeInMillis() + "");
                mapToJsp.put("nonceStr", RandomStringGenerator.getRandomStringByLength(32));
                mapToJsp.put("package", "prepay_id=" + prepay_id);
                mapToJsp.put("signType", "MD5");
                String paySign = signature.getSign(mapToJsp);
                System.out.println("paySign+++" + paySign);
                mapToJsp.put("packageValue", "prepay_id=" + prepay_id);
                mapToJsp.put("paySign", paySign);
                mapToJsp.put("orderCode", orderCode);
                String requestGetMemberInfoUrl = Configure.requestGetMemberInfo;
                requestGetMemberInfoUrl = requestGetMemberInfoUrl.replace("ACCESS_TOKEN", accessToken);
                requestGetMemberInfoUrl = requestGetMemberInfoUrl.replace("OPENID", member.getOpenid());
                requestGetMemberInfoUrl = requestGetMemberInfoUrl.replace("zh_CN", Configure.language_CN);

                net.sf.json.JSONObject jsonObj = NetTools.httpsRequest(requestGetMemberInfoUrl, "GET", null);
                Integer subscribe = (Integer) jsonObj.get("subscribe");
                if (subscribe != null) {
                    mapToJsp.put("subscribe", subscribe.toString());
                } else {
                    mapToJsp.put("subscribe", "1");
                }
                memberStoreOrderService.save(order);
                return JSONObject.toJSONString(mapToJsp);
            } else {
                return JSONObject.toJSONString(return_msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        model.addAttribute("result", "success");
        return JSONObject.toJSONString(model);
    }


    /**
     * 餐卡二维码支付,获取校验码
     *
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/getCode", method = RequestMethod.POST)
    @ResponseBody
    public String getCode(Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo member = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        if (!StringUtils.hasText(member.getIdNumber())) {
            model.addAttribute("result", "fail");
            model.addAttribute("message", "暂未关联餐卡");
            return JSONObject.toJSONString(model);
        }
        String paySign = "";
        String idNumber = member.getIdNumber();
        String substring = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 5);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMddHHmmss");
        String time = formatter.format(LocalDateTime.now());
        paySign += idNumber + substring + time;
//        paySign+=idNumber+substring+time+QR_PASSWORD;
        paySign = MD5.MD5Encode(paySign).toUpperCase();
        String result = paySign + "&" + time + "&" + substring;
        return JSONObject.toJSONString(result + "&" + idNumber);
    }


    /**
     * 餐卡储值记录
     *
     * @param model
     * @param request
     * @param response
     * @return
     */

    @RequestMapping(value = "/storedRecord", method = RequestMethod.POST)
    @ResponseBody
    public String manageStoreRecordList(Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo loginUser = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);

        String startTime = request.getParameter("startTime");//只获取到天
        String endTime = request.getParameter("endTime");
        if (StringUtils.isEmpty(startTime)) {
            startTime = "2015-04-15";
        }
        if (StringUtils.isEmpty(endTime)) {
            endTime = TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd");
        }

        String pospubUrl = kongxc_pos_http_server_url;
        if (StringTools.hasText(pospubUrl)) {
            HttpUtil send = new HttpUtil(pospubUrl);
            ObjectToXML toXml = new ObjectToXML();

            String uuid2 = UUID.randomUUID().toString().replace("-", "");
            MemberBaseInfoModel account = new MemberBaseInfoModel();
            account.setRequestUnique(uuid2);
            String requestStoreXml = toXml.requestStoredXML(PROPASS, CUS_NAME, PROJECT_CODE, loginUser.getIdNumber(), loginUser.getZfPasswd(), uuid2, startTime, endTime);
            System.out.println(requestStoreXml);
            try {
                logger.info("oos request to pos start.query the storedRecord.time=" + TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ".currentTimeMillis=" + System.currentTimeMillis() + ".name=" + loginUser.getLoginName());
                String responseStoreXML = send.sendToBoss(requestStoreXml);
                logger.info("pos responese oos end get the storedRecord.time=" + TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ".currentTimeMillis=" + System.currentTimeMillis() + ".name=" + loginUser.getLoginName());
                if ("0000".equals(toXml.resolveStoredXML(responseStoreXML, request))) {
                    List<CardStoredModel> storeList = (List<CardStoredModel>) request.getAttribute("storeList");
                    if (storeList.size() > 0) {
                        model.addAttribute("resoult", "success");
                        model.addAttribute("list", storeList);
                        return JSONObject.toJSONString(model);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return "数据加载失败";
        }
        model.addAttribute("resoult", "fail");
        model.addAttribute("message", "该时间段未查询到记录");
        return JSONObject.toJSONString(model);
    }


    /**
     * 餐卡消费记录
     *
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/consumeRecord", method = RequestMethod.POST)
    @ResponseBody
    public String manageConsumeRecordList(Model model, HttpServletRequest request, HttpServletResponse response) {
        MemberBaseInfo loginUser = (MemberBaseInfo) WebUtils.getSessionAttribute(request, SessionNames.LOGIN_USER);
        String startTime = request.getParameter("startTime");
        String endTime = request.getParameter("endTime");
        if (StringUtils.isEmpty(startTime)) {
            startTime = "2015-04-15 00:00:00";
        } else {
            startTime += " 00:00:00";
        }
        if (StringUtils.isEmpty(endTime)) {
            endTime = TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd 23:59:59");
        } else {
            endTime += " 23:59:59";
        }
        String pospubUrl = kongxc_pos_http_server_url;
        if (StringTools.hasText(pospubUrl)) {
            HttpUtil send = new HttpUtil(pospubUrl);
            ObjectToXML toXml = new ObjectToXML();

            String uuid = UUID.randomUUID().toString().replace("-", "");
            MemberBaseInfoModel account = new MemberBaseInfoModel();
            account.setRequestUnique(uuid);
            String resultXml = toXml.requestGetPosCon(PROPASS, CUS_NAME, loginUser.getSchool().getCode(), loginUser, startTime, endTime);
//            String requestStoreXml = toXml.requestConsumptionRecord(PROPASS, CUS_NAME, PROJECT_CODE, loginUser.getIdNumber(), loginUser.getZfPasswd(), startTime, endTime, uuid);
            try {
                logger.info("oos request to pos start.query the consumeRecord.time=" + TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ".currentTimeMillis=" + System.currentTimeMillis() + ".name=" + loginUser.getLoginName());
                String responseXml = send.sendToBoss(resultXml);
                logger.info("pos responese oos end get the consumeRecord.time=" + TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ".currentTimeMillis=" + System.currentTimeMillis() + ".name=" + loginUser.getLoginName());
                if ("0000".equals(toXml.resolveGetTodCon(responseXml))) {
                    List<OrderOfDaynut> conList = toXml.resolveGetTodConDet(responseXml);
                    if (conList.size() > 0) {
                        model.addAttribute("resoult", "success");
                        model.addAttribute("list", conList);
                        return JSONObject.toJSONString(model);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            return "数据加载失败";
        }
        model.addAttribute("resoult", "fail");
        model.addAttribute("message", "该时间段未查询到记录");
        return JSONObject.toJSONString(model);
    }

    /**
     * 餐卡消费记录,储值记录
     *
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/allRecord", method = RequestMethod.POST)
    @ResponseBody
    public String allRecordList(Model model, HttpServletRequest request, HttpServletResponse response) {
        JSONObject consumeRecordJSON = JSONObject.parseObject(manageConsumeRecordList(model, request, response));
        JSONObject storeRecordJSON = JSONObject.parseObject(manageStoreRecordList(model, request, response));
        List<JSONObject> jsonObjectList = new ArrayList<>();
        if ("success".equals(consumeRecordJSON.get("resoult"))) {
            List<JSONObject> conList = JSONObject.parseArray(consumeRecordJSON.getString("list"), JSONObject.class);
            jsonObjectList.addAll(conList);
        }
        if ("success".equals(storeRecordJSON.get("resoult"))) {
            List<JSONObject> storeList = JSONObject.parseArray(storeRecordJSON.getString("list"), JSONObject.class);
            jsonObjectList.addAll(storeList);
        }
        Comparator<JSONObject> comparator = (o1, o2) -> Integer.compare(0, o1.getString("sortTime").compareTo(o2.getString("sortTime")));
        jsonObjectList.sort(comparator);
        if (jsonObjectList.size() > 0) {
            model.addAttribute("resoult", "success");
            model.addAttribute("consumeRecord", jsonObjectList);
        } else {
            model.addAttribute("resoult", "fail");
            model.addAttribute("message", "该时间段未查询到记录");
        }

        return JSONObject.toJSONString(model);
    }


    /**
     * 关联用户餐卡
     *
     * @param model
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/linkCardAccount", method = RequestMethod.POST)
    @ResponseBody
    public String openCardAccount(@RequestBody MemberBaseInfo entity, Model model, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        MemberBaseInfo loginUser = (MemberBaseInfo) WebUtils.getSessionAttribute(request, MySessionNames.LOGIN_USER);
        loginUser.setSchoolCode(loginUser.getSchool().getCode());
        /*-----------------根据手机号码到pos取个人信息-----------*/
        DiancanSchoolurl dianCanSchoolUrl = diancanSchoolurlService.queryByCodeAndStatus(loginUser.getSchoolCode(), DiancanSchoolurl.IsEffect.YX);
        HttpUtil send = new HttpUtil(dianCanSchoolUrl.getPosUrl());
        ObjectToXML toXml = new ObjectToXML();
        String resultXml = toXml.requestGetMemInfo(dianCanSchoolUrl.getPosPropass(), dianCanSchoolUrl.getPosCusName(), loginUser.getSchoolCode(), entity);
        System.out.println("resultXml----------------" + resultXml);
        String responseRegistXml = null;
        logger.info("oos request to pos start.registe the user.time=" + TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ".currentTimeMillis=" + System.currentTimeMillis() + ".name=" + entity.getLoginName());
        try {
            responseRegistXml = send.sendToBoss(resultXml);
        } catch (Exception e) {
            logger.debug(e.getMessage());
        }
        System.err.println("responseRegistXml>>>" + responseRegistXml);
        logger.info("oos request to pos start.registe end.time=" + TimeTools.calendar2String(Calendar.getInstance(), "yyyy-MM-dd HH:mm:ss") + ".currentTimeMillis=" + System.currentTimeMillis() + ".name=" + entity.getLoginName());

        MemberBaseInfo memberBaseInfo = toXml.resolveGetMemInfo(responseRegistXml);
        if ("0000".equals(memberBaseInfo.getResponseCode())) {
            if ("1".equals(memberBaseInfo.getStatus())) {
                String json = "{\"result\":\"false\",\"message\":\"该用户已被停用\"}";
                return json;
            }
            CustomerMinMum customerMinMum = customerMinMumService.query().eq("customer_type_id", memberBaseInfo.getCustomerType()).one();
            if (customerMinMum == null) {
                customerMinMum = new CustomerMinMum();
                customerMinMum.setCustomerTypeId(memberBaseInfo.getCustomerType());
            }
            customerMinMum.setMorningMinMum(memberBaseInfo.getMorningMinMum());
            customerMinMum.setAfternoonMinMum(memberBaseInfo.getAfternoonMinMum());
            customerMinMum.setEvenningMinMum(memberBaseInfo.getEvenningMinMum());
            customerMinMum.setMorningAllowance(memberBaseInfo.getMorningAllowance());
            customerMinMum.setAfternoonAllowance(memberBaseInfo.getAfternoonAllowance());
            customerMinMum.setEveningAllowance(memberBaseInfo.getEvenningAllowance());
            customerMinMumService.saveOrUpdate(customerMinMum);
            loginUser.setIdNumber(memberBaseInfo.getIdNumber());
            loginUser.setMobile(memberBaseInfo.getMobile());
            loginUser.setLoginName(memberBaseInfo.getMobile());
            //支付密码暂未使用,设置为顾客id
            loginUser.setZfPasswd(memberBaseInfo.getIdNumber());
            loginUser.setPasswd(memberBaseInfo.getIdNumber());
            loginUser.setCustomerType(memberBaseInfo.getCustomerType());
            memberBaseInfoService.updateById(loginUser);
            //推送注册结果到POS
            String params = "?customerNo=" + memberBaseInfo.getIdNumber() + "&openId=" + memberBaseInfo.getOpenid();
            HttpClientUtil.sendPost(POS_URL + "/app/card/customer/registerWeChat" + params, null);
            WebUtils.setSessionAttribute(request, MySessionNames.LOGIN_USER, loginUser);
            model.addAttribute("result", "success");
            model.addAttribute("message", "成功关联餐卡");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        } else {
            model.addAttribute("result", "false");
            model.addAttribute("message", "未查询到餐卡信息");
            return JSONObject.toJSONString(model, SerializerFeature.IgnoreNonFieldGetter);
        }
    }

    /**
     * 餐卡二维码扫描结果通知
     */
    @RequestMapping(value = "/QRpayResult", method = RequestMethod.POST)
    @ResponseBody
    public String QRpayResult(CoursesOrders coursesOrders) {
        HashMap<String, String> resultMap = new HashMap<>();
        resultMap.put("result", "success");
        net.sf.json.JSONObject jsonObject = new net.sf.json.JSONObject();
        MemberBaseInfo memberInfo = memberBaseInfoService.findByProperty("Id_Number", coursesOrders.getCustomerNo());
        if (memberInfo != null) {
            String accessToken = accesstokensaveService.getOne(new QueryWrapper<>(), false).getAccessToken();
            switch (coursesOrders.getStatus()) {
                case WCTK:
                    //退款
                    jsonObject = orderSend.tuiKunMethod(accessToken, memberInfo, coursesOrders, null);
                    break;
                case YZF:
                    //支付
                    userMap.put(coursesOrders.getCustomerNo(), coursesOrders);
                    jsonObject = orderSend.sendMet(accessToken, memberInfo, coursesOrders.getOrderCode(), null);
                    break;
                case CZ:
                    //储值
                    jsonObject = orderSend.chuzhiMethod(accessToken, memberInfo, coursesOrders);
                    break;
                default:
                    break;
            }
        }
        if (jsonObject.getInt("errcode") != 0) {
            resultMap.put("result", "fail");
            resultMap.put("message", jsonObject.getString("errmsg"));
        }
        return JSONObject.toJSONString(resultMap);
    }

    /**
     * 客户端轮询接口
     */
    @RequestMapping(value = "/getQRpayResult", method = RequestMethod.POST)
    @ResponseBody
    public String getQRpayResult(Model model, HttpServletRequest request) {
        String customerNo = request.getParameter("customerNo");
        if (userMap.containsKey(customerNo)) {
            try {
                model.addAttribute("result", "success");
                model.addAttribute("message", userMap.get(customerNo).getAmount());
                return JSONObject.toJSONString(model);
            } finally {
                userMap.remove(customerNo);
            }
        } else {
            model.addAttribute("result", "fail");
            return JSONObject.toJSONString(model);
        }
    }


}
